﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Threading;

namespace IBNet.LongTermTrade
{
   static class LongTermTradeProgram
   {
      public static int LongTermTradeOcaNumber;

      static void Main()
      {
         string ocaNumberFilepath = "..\\..\\..\\LongTermTradeOcaNumber.txt";
         if (!File.Exists(ocaNumberFilepath))
         {
            MessageBox.Show(ocaNumberFilepath + " (three folders above LongTermTrade.exe) must exist to run this program.\r\nWhen creating LongTermTradeOcaNumber.txt for the first time, its contents should be '1' on line 1.", 
               "Error: " + ocaNumberFilepath + " must exist to run this program.");
            Environment.Exit(1);
         }

         // Use mutex to allow only one instance of LongTermTrade.exe.
         bool ownsMutex;
         using (Mutex mutex = new Mutex(true, "LongTermTrade.exe", out ownsMutex))
         {
            if (ownsMutex)
            {
               string ocaNumberAsString = File.ReadAllLines(ocaNumberFilepath)[0];
               LongTermTradeProgram.LongTermTradeOcaNumber = 
                  Int32.Parse(ocaNumberAsString);

               Application.EnableVisualStyles();
               Application.Run(new LongTermTradeMainForm());

               ocaNumberAsString = LongTermTradeOcaNumber.ToString();
               File.WriteAllText(ocaNumberFilepath, ocaNumberAsString);
            }
            else
            {
               MessageBox.Show("Only one instance of LongTermTrade.exe can be running at a time.", "Error");
            }
         }
      }
   }
}
